<?php

/**
 * 模板调用
 * @param $template public/header
 * @param $module
 * @return unknown_type
 */
function template($template = 'index', $module = '') {
    $module = empty($module) ? MODULE_NAME : $module;

    $config = ticky\config::get('view');
    $driver = $config['driver']; //smarty
    $suffix = $config[$driver]['template_suffix']; //html
    $theme = $config['default_theme']; //default
    $view_path = APP_PATH . DS . $module . DS . 'view';  // application/XXX/view
    $viewName = $template;
    $viewFiles = array(
        $viewName,
        $view_path . DS . ACTION_NAME, // application/XXX/view/index
        $view_path . DS . CONTROLLER_NAME . DS . ACTION_NAME, // application/XXX/view/home/index
        $view_path . DS . $theme . DS . $viewName . '.' . $suffix, // application/XXX/view/theme/index.html
        $view_path . DS . $theme . DS . CONTROLLER_NAME . DS . $viewName . '.' . $suffix, // application/XXX/view/theme/home/index.html
        $view_path . DS . $theme . DS . $viewName . '.' . $suffix, // application/XXX/view/theme/index.html
        $view_path . DS . $theme . DS . CONTROLLER_NAME . DS . $viewName . '.' . $suffix, // application/XXX/view/theme/home/index.html
        $view_path . DS . $viewName . '.' . $suffix, // application/XXX/view/home/index
        $view_path . DS . CONTROLLER_NAME . DS . ACTION_NAME . '.' . $suffix, // application/XXX/view/home/index.html
    );
    if (!is_file($viewName)) {
        foreach ($viewFiles as $x => $x_value) {
            if (is_file($x_value)) {
                $tplfile = $x_value;
                break;
            }
        }
    } else {
        $tplfile = $viewName;
    }
    if (!is_file($tplfile)) {
        showmsg($template . L('template_does_not_exist'), 'stop');
    }
    return $tplfile;
}

function debug($var = null, $vardump = false) {
    echo '<pre>';
    $vardump = empty($var) ? true : $vardump;
    if ($vardump) {
        var_dump($var);
    } else {
        print_r($var);
    }
    echo '</pre>';
    exit();
}

/**
 * 对用户的密码进行加密
 * @param $pass 字符串
 * @return string 字符串
 */
function password($pass) {
    return authcode($pass, 'ENCODE');
}

function dstrlen($str) {
    if (strtolower(CHARSET) != 'utf-8') {
        return strlen($str);
    }
    $count = 0;
    for ($i = 0; $i < strlen($str); $i++) {
        $value = ord($str[$i]);
        if ($value > 127) {
            $count++;
            if ($value >= 192 && $value <= 223)
                $i++;
            elseif ($value >= 224 && $value <= 239)
                $i = $i + 2;
            elseif ($value >= 240 && $value <= 247)
                $i = $i + 3;
        }
        $count++;
    }
    return $count;
}

if (!function_exists('get_dir_chmod')) {

    function get_dir_chmod($dirName) {
        if (is_readable($dirName)) {
            $chmod = '可读,';
        }
        if (is_writable($dirName)) {
            $chmod .= '可写,';
        }
        if (is_executable($dirName)) {
            $chmod .= '可执行,';
        }
        return trim($chmod, ',');
    }

}

/**
 * 获取请求地区
 * @param $ip
 * @return 所在位置
 */
function get_ip_address($ip = '', $type = null) {
    if (!$ip) {
        $ip = \ticky\request::getClientIp();
    }
    $url = "http://ip.taobao.com/service/getIpInfo.php?ip=" . $ip;
    //调用淘宝接口获取信息
    $json = file_get_contents($url);
    $data = json_decode($json, true);
    if ($data['code']) {
        return $data['data'];
    } else {
        $country = $data['data']['country'];
        $province = $data['data']['region'];
        $city = $data['data']['city'];
        $area = $data['data']['area'];
        if ($type == 'country') {
            return $country;
        } elseif ($type == 'province') {
            return $province;
        } elseif ($type == 'area') {
            return $area;
        } elseif ($type == 'city') {
            return $city;
        } else {
            return $country . ' ' . ' ' . $province . ' ' . $city;
        }
    }
}

/**
 * 创建订单号
 *
 * @return   string     字符串
 */
function create_tradenum() {
    return date('YmdHis') . random(4);
}

/**
 * 记录日志
 * @param $file 日志文件
 * @param $message 日志信息
 * @param $halt exit()
 * @return bool
 */
function runlog($file, $message, $halt = 0) {
    global $_G;
    if (is_array($message)) {
        $message = implode(",", $message);
    }
    $nowurl = $_SERVER['REQUEST_URI'] ? $_SERVER['REQUEST_URI'] : ($_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME']);
    $username = $_G['username'];
    $log = date('Y-m-d H:i:s') . "\t" . getip() . "\t" . $username . "\t{$nowurl}\t" . str_replace(array("\r", "\n"), array(' ', ' '), trim($message)) . "\n";
    \ticky\helper\file::writelog($file, $log);
    if ($halt) {
        exit();
    }
}

/**
 * 产生随机码
 * @param $length - 要多长
 * @param $numeric - 数字还是字符串
 * @return 返回字符串
 */
function random($length, $numeric = 0) {
    $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
    $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
    if ($numeric) {
        $hash = '';
    } else {
        $hash = chr(rand(1, 26) + rand(0, 1) * 32 + 64);
        $length--;
    }
    $max = strlen($seed) - 1;
    for ($i = 0; $i < $length; $i++) {
        $hash .= $seed{mt_rand(0, $max)};
    }
    return $hash;
}

/**
 * 判断一个字符串是否在另一个字符串中存在
 *
 * @param string 原始字串 $string
 * @param string 查找 $find
 * @return boolean
 */
function strexists($string, $find) {
    return !(strpos($string, $find) === FALSE);
}

/**
 * 根据中文裁减字符串
 * @param $string - 字符串
 * @param $length - 长度
 * @param $dot - 缩略后缀
 * @return 返回带省略号被裁减好的字符串
 */
function cutstr($string, $length, $dot = '...') {
    if (strlen($string) <= $length) {
        return $string;
    }
    $pre = chr(1);
    $end = chr(1);
    $string = str_replace(array('&amp;', '&quot;', '&lt;', '&gt;'), array($pre . '&' . $end, $pre . '"' . $end, $pre . '<' . $end, $pre . '>' . $end), $string);
    $strcut = '';
    if (strtolower(CHARSET) == 'utf-8') {
        $n = $tn = $noc = 0;
        while ($n < strlen($string)) {
            $t = ord($string[$n]);
            if ($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
                $tn = 1;
                $n++;
                $noc++;
            } elseif (194 <= $t && $t <= 223) {
                $tn = 2;
                $n += 2;
                $noc += 2;
            } elseif (224 <= $t && $t <= 239) {
                $tn = 3;
                $n += 3;
                $noc += 2;
            } elseif (240 <= $t && $t <= 247) {
                $tn = 4;
                $n += 4;
                $noc += 2;
            } elseif (248 <= $t && $t <= 251) {
                $tn = 5;
                $n += 5;
                $noc += 2;
            } elseif ($t == 252 || $t == 253) {
                $tn = 6;
                $n += 6;
                $noc += 2;
            } else {
                $n++;
            }

            if ($noc >= $length) {
                break;
            }
        }
        if ($noc > $length) {
            $n -= $tn;
        }

        $strcut = substr($string, 0, $n);
    } else {
        $_length = $length - 1;
        for ($i = 0; $i < $length; $i++) {
            if (ord($string[$i]) <= 127) {
                $strcut .= $string[$i];
            } else if ($i < $_length) {
                $strcut .= $string[$i] . $string[++$i];
            }
        }
    }

    $strcut = str_replace(array($pre . '&' . $end, $pre . '"' . $end, $pre . '<' . $end, $pre . '>' . $end), array('&amp;', '&quot;', '&lt;', '&gt;'), $strcut);

    $pos = strrpos($strcut, chr(1));
    if ($pos !== false) {
        $strcut = substr($strcut, 0, $pos);
    }
    return $strcut . $dot;
}

function pass_time($time) {
    $now = time();
    $time_past = $now - strtotime($time);

    // 如果小于1分钟（60s），则显示"刚刚"
    if ($time_past < 60) {
        return '刚刚';
    }

    $time_mapping = array(
        '分钟' => '60',
        '小时' => '24',
        '天' => '7',
        '周' => '4',
        '月' => '12',
        '年' => '100'
    );

    $time_past = floor($time_past / 60);

    foreach ($time_mapping as $k => $v) {
        if ($time_past < $v) {
            return floor($time_past) . $k . '前';
        }
        $time_past = $time_past / $v;
    }

    // 如果小于1小时（60*60s），则显示N分钟前
    // 如果小于24个小时（60*60*24s），则显示N小时前
    // 如果大于24个小时（60*60*24s），则显示N天前
}

function dstripslashes($string) {
    if (empty($string))
        return $string;
    if (is_array($string)) {
        foreach ($string as $key => $val) {
            $string[$key] = dstripslashes($val);
        }
    } else {
        $string = stripslashes($string);
    }
    return $string;
}

/**
 * 字节格式化单位
 * @param $filesize - 大小(字节)
 * @return 返回格式化后的文本
 */
function sizecount($size) {
    if ($size >= 1073741824) {
        $size = round($size / 1073741824 * 100) / 100 . ' GB';
    } elseif ($size >= 1048576) {
        $size = round($size / 1048576 * 100) / 100 . ' MB';
    } elseif ($size >= 1024) {
        $size = round($size / 1024 * 100) / 100 . ' KB';
    } else {
        $size = intval($size) . ' Bytes';
    }
    return $size;
}

/**
 * ip允许访问
 * @param $ip 要检查的ip地址
 * @param - $accesslist 允许访问的ip地址
 * @param 返回结果
 */
function ipaccess($ip, $accesslist) {
    return preg_match("/^(" . str_replace(array("\r\n", ' '), array('|', ''), preg_quote($accesslist, '/')) . ")/", $ip);
}

function dintval($int, $allowarray = false) {
    $ret = intval($int);
    if ($int == $ret || !$allowarray && is_array($int))
        return $ret;
    if ($allowarray && is_array($int)) {
        foreach ($int as &$v) {
            $v = dintval($v, true);
        }
        return $int;
    } elseif ($int <= 0xffffffff) {
        $l = strlen($int);
        $m = substr($int, 0, 1) == '-' ? 1 : 0;
        if (($l - $m) === strspn($int, '0987654321', $m)) {
            return $int;
        }
    }
    return $ret;
}

function dmkdir($dir, $mode = 0777, $makeindex = TRUE) {
    if (!is_dir($dir)) {
        dmkdir(dirname($dir), $mode, $makeindex);
        @mkdir($dir, $mode);
        if (!empty($makeindex)) {
            @touch($dir . '/index.html');
            @chmod($dir . '/index.html', 0777);
        }
    }
    return true;
}

/**
 * xss过滤函数
 *
 * @param $string
 * @return string
 */
function remove_xss($string) {
    $string = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]+/S', '', $string);
    $parm1 = Array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base');
    $parm2 = Array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload');
    $parm = array_merge($parm1, $parm2);
    for ($i = 0; $i < sizeof($parm); $i++) {
        $pattern = '/';
        for ($j = 0; $j < strlen($parm[$i]); $j++) {
            if ($j > 0) {
                $pattern .= '(';
                $pattern .= '(&#[x|X]0([9][a][b]);?)?';
                $pattern .= '|(&#0([9][10][13]);?)?';
                $pattern .= ')?';
            }
            $pattern .= $parm[$i][$j];
        }
        $pattern .= '/i';
        $string = preg_replace($pattern, ' ', $string);
    }
    return $string;
}

/**
 * 安全过滤函数
 *
 * @param $string
 * @return string
 */
function safe_replace($string) {
    $string = str_replace('%20', '', $string);
    $string = str_replace('%27', '', $string);
    $string = str_replace('%2527', '', $string);
    $string = str_replace('*', '', $string);
    $string = str_replace('"', '', $string);
    $string = str_replace("'", '', $string);
    $string = str_replace(';', '', $string);
    $string = str_replace('<', '&lt;', $string);
    $string = str_replace('>', '&gt;', $string);
    $string = str_replace("{", '', $string);
    $string = str_replace('}', '', $string);
    $string = str_replace('\\', '', $string);
    return $string;
}

/**
 * IE浏览器判断
 */
function is_ie() {
    $useragent = strtolower($_SERVER['HTTP_USER_AGENT']);
    if ((strpos($useragent, 'opera') !== false) || (strpos($useragent, 'konqueror') !== false)) {
        return false;
    }
    if (strpos($useragent, 'msie ') !== false) {
        return true;
    }
    return false;
}

/**
 * 判断email格式是否正确
 * @param $email
 */
function is_email($email) {
    return strlen($email) > 6 && preg_match("/^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/", $email);
}

/**
 * 判断手机格式是否正确
 * @param $mobile
 */
function is_mobile($mobile) {
    return preg_match('/1[3456789]{1}\d{9}$/', $mobile);
}

/**
 * 检测输入中是否含有错误字符
 *
 * @param char $string 要检查的字符串名称
 * @return TRUE or FALSE
 */
function is_badword($string) {
    $badwords = array("\\", '&', ' ', "'", '"', '/', '*', ',', '<', '>', "\r", "\t", "\n", "#");
    foreach ($badwords as $value) {
        if (strpos($string, $value) !== false) {
            return true;
        }
    }
    return false;
}

/**
 * 取得文件扩展
 *
 * @param $filename 文件名
 * @return 扩展名
 */
function fileext($filename) {
    return strtolower(trim(substr(strrchr($filename, '.'), 1, 10)));
}

/**
 * 文件下载
 * @param $filepath 文件路径
 * @param $filename 文件名称
 */
function file_down($filepath, $filename = '') {
    if (!$filename) {
        $filename = basename($filepath);
    }
    if (is_ie()) {
        $filename = rawurlencode($filename);
    }
    $filetype = fileext($filename);
    $filesize = sprintf("%u", filesize($filepath));
    if (ob_get_length() !== false) {
        @ob_end_clean();
    }
    header('Pragma: public');
    header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
    header('Cache-Control: no-store, no-cache, must-revalidate');
    header('Cache-Control: pre-check=0, post-check=0, max-age=0');
    header('Content-Transfer-Encoding: binary');
    header('Content-Encoding: none');
    header('Content-type: ' . $filetype);
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    header('Content-length: ' . $filesize);
    readfile($filepath);
    exit;
}

/**
 * 将字符串转换为数组
 *
 * @param	string	$data	字符串
 * @return	array	返回数组格式，如果，data为空，则返回空数组
 */
function string2array($data) {
    $data = trim($data);
    if ($data == '')
        return array();

    if (strpos($data, '{\\') === 0)
        $data = stripslashes($data);
    $array = json_decode($data, true);
    return $array;
}

/**
 * 将数组转换为字符串
 *
 * @param	array	$data		数组
 * @param	bool	$isformdata	如果为0，则不使用new_stripslashes处理，可选参数，默认为1
 * @return	string	返回字符串，如果，data为空，则返回空
 */
function array2string($data, $isformdata = 1) {
    if ($data == '' || empty($data))
        return '';

    if ($isformdata)
        $data = new_stripslashes($data);
    if (version_compare(PHP_VERSION, '5.3.0', '<')) {
        return addslashes(json_encode($data));
    } else {
        return addslashes(json_encode($data, JSON_FORCE_OBJECT));
    }
}

/**
 * 对数据进行编码转换
 * @param array/string $data       数组
 * @param string $input     需要转换的编码
 * @param string $output    转换后的编码
 */
function array_iconv($data, $input = 'gbk', $output = 'utf-8') {
    if (!is_array($data)) {
        return iconv($input, $output, $data);
    } else {
        foreach ($data as $key => $val) {
            if (is_array($val)) {
                $data[$key] = array_iconv($val, $input, $output);
            } else {
                $data[$key] = iconv($input, $output, $val);
            }
        }
        return $data;
    }
}

/**
 * 返回经stripslashes处理过的字符串或数组
 * @param $string 需要处理的字符串或数组
 * @return mixed
 */
function new_stripslashes($string) {
    if (!is_array($string))
        return stripslashes($string);
    foreach ($string as $key => $val) {
        $string[$key] = new_stripslashes($val);
    }
    return $string;
}

/**
 * 返回经htmlspecialchars处理过的字符串或数组
 * @param $obj 需要处理的字符串或数组
 * @return mixed
 */
function new_html_special_chars($string) {
    if (!is_array($string))
        return htmlspecialchars($string, ENT_QUOTES, 'utf-8');
    foreach ($string as $key => $val)
        $string[$key] = new_html_special_chars($val);
    return $string;
}

/**
 * 转义 javascript 代码标记
 *
 * @param $str
 * @return mixed
 */
function trim_script($str) {
    if (is_array($str)) {
        foreach ($str as $key => $val) {
            $str[$key] = trim_script($val);
        }
    } else {
        $str = preg_replace('/\<([\/]?)script([^\>]*?)\>/si', '&lt;\\1script\\2&gt;', $str);
        $str = preg_replace('/\<([\/]?)iframe([^\>]*?)\>/si', '&lt;\\1iframe\\2&gt;', $str);
        $str = preg_replace('/\<([\/]?)frame([^\>]*?)\>/si', '&lt;\\1frame\\2&gt;', $str);
        $str = str_replace('javascript:', 'javascript：', $str);
    }
    return $str;
}

/**
 * 获取内容中的图片
 * @param string $content 内容
 * @return string
 */
function match_img($content) {
    preg_match('/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg]))[\'|\"].*?[\/]?>/', $content, $match);
    return !empty($match) ? $match[1] : '';
}

/**
 * 获取远程图片并把它保存到本地, 确定您有把文件写入本地服务器的权限
 * @param string $content 文章内容
 * @param string $targeturl 可选参数，对方网站的网址，防止对方网站的图片使用"/upload/1.jpg"这样的情况
 * @return string $content 处理后的内容
 */
function grab_image($content, $targeturl = '') {
    preg_match_all('/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg]))[\'|\"].*?[\/]?>/', $content, $img_array);
    $img_array = isset($img_array[1]) ? array_unique($img_array[1]) : array();

    if ($img_array) {
        $path = RUNTIME_PATH . DS . 'uploads' . DS . date('Ym/d');
        $urlpath = SITE_URL . $path;
        $imgpath = $path;
        if (!is_dir($imgpath))
            @mkdir($imgpath, 0777, true);
    }

    foreach ($img_array as $key => $value) {
        $val = $value;
        if (strpos($value, 'http') === false) {
            if (!$targeturl) {
                return $content;
            }
            $value = $targeturl . $value;
        }
        $ext = strrchr($value, '.');
        if ($ext != '.png' && $ext != '.jpg' && $ext != '.gif' && $ext != '.jpeg')
            return false;
        $imgname = date("YmdHis") . rand(1, 9999) . $ext;
        $filename = $imgpath . '/' . $imgname;
        $urlname = $urlpath . '/' . $imgname;

        ob_start();
        readfile($value);
        $data = ob_get_contents();
        ob_end_clean();
        file_put_contents($filename, $data);

        if (is_file($filename)) {
            $content = str_replace($val, $urlname, $content);
        } else {
            return $content;
        }
    }
    return $content;
}

/**
 * 生成缩略图函数
 * @param  $imgurl 图片路径
 * @param  $width  缩略图宽度
 * @param  $height 缩略图高度
 * @param  $autocut 是否自动裁剪 默认不裁剪，当高度或宽度有一个数值为0时，自动关闭
 * @param  $smallpic 无图片是默认图片路径
 * @return string
 */
function thumb($imgurl, $width = 300, $height = 200, $autocut = 0, $smallpic = 'nopic.jpg') {
    global $image;
    $upload_url = SITE_URL . 'uploads/';
    $upload_path = RUNTIME_PATH . DS . 'uploads' . DS . date('Ym/d');
    if (empty($imgurl))
        return STATIC_URL . 'images/' . $smallpic;
    if (!strpos($imgurl, '://'))
        $imgurl = SERVER_PORT . HTTP_HOST . $imgurl;
    $imgurl_replace = str_replace($upload_url, '', $imgurl);
    if (!extension_loaded('gd') || strpos($imgurl_replace, '://'))
        return $imgurl;
    if (!is_file($upload_path . $imgurl_replace))
        return STATIC_URL . 'images/' . $smallpic;

    list($width_t, $height_t, $type, $attr) = getimagesize($upload_path . $imgurl_replace);
    if ($width >= $width_t || $height >= $height_t)
        return $imgurl;

    $newimgurl = dirname($imgurl_replace) . '/thumb_' . $width . '_' . $height . '_' . basename($imgurl_replace);

    if (is_file($upload_path . $newimgurl))
        return $upload_url . $newimgurl;

    if (!is_object($image)) {
        $image = new image(1);
    }
    return $image->thumb($upload_path . $imgurl_replace, $upload_path . $newimgurl, $width, $height, '', $autocut) ? $upload_url . $newimgurl : $imgurl;
}

/**
 * 水印添加
 * @param $source 原图片路径
 * @param $target 生成水印图片途径，默认为空，覆盖原图
 * @return string
 */
function watermark($source, $target = '') {
    global $image_w;
    if (empty($source))
        return $source;
    if (!extension_loaded('gd') || strpos($source, '://'))
        return $source;
    if (!$target)
        $target = $source;
    if (!is_object($image_w)) {
        load::load_sys_class('image', '', '0');
        $image_w = new image(1, 1);
    }
    $image_w->watermark($source, $target);
    return $target;
}

/**
 * HTML自动补全
 * @param $html 原图片路径
 * @return string
 */
function closetags($html) {
    preg_match_all('#<(?!meta|img|br|hr|input\b)\b([a-z]+)(?: .*)?(?<![/|/ ])>#iU', $html, $result);
    $openedtags = $result[1];
    preg_match_all('#</([a-z]+)>#iU', $html, $result);
    $closedtags = $result[1];
    $len_opened = count($openedtags);
    if (count($closedtags) == $len_opened) {
        return $html;
    }
    $openedtags = array_reverse($openedtags);
    for ($i = 0; $i < $len_opened; $i++) {
        if (!in_array($openedtags[$i], $closedtags)) {
            $html .= '</' . $openedtags[$i] . '>';
        } else {
            unset($closedtags[array_search($openedtags[$i], $closedtags)]);
        }
    }
    return $html;
}

/**
 * 返回json数组，默认提示 “数据未修改！”
 * @param $arr
 * @return string
 */
function return_json($arr = array()) {
    if (!$arr)
        exit(json_encode(array('status' => 0, 'message' => L('data_not_modified'))));
    exit(json_encode($arr));
}

function formhash($specialadd = '') {
    global $_G;
    $hashadd = defined('IN_ADMIN') ? 'Only For Admin Control Panel' : '';
    return substr(md5(substr($_G['timestamp'], 0, -7) . $_G['username'] . $_G['uid'] . 'luomingui' . $hashadd . $specialadd), 8, 8);
}

/** 检查文件
 * @param  string $currentdir    //待检查目录
 * @param  string $ext           //待检查的文件类型
 * @param  int    $sub           //是否检查子目录
 * @param  string $skip          //不检查的目录或文件
 */
function checkfiles($currentdir, $ext = '\.php|\.html|\.htm|\.js|\.css', $sub = 1, $skip = '.scannerwork,runtime,static,vendor,extend') {
    global $_G;
    $dir = @opendir(ROOT_PATH . $currentdir);
    $exts = '/(' . $ext . ')$/i';
    $skips = explode(',', $skip);
    while ($entry = @readdir($dir)) {
        $file = $currentdir . $entry;
        if ($entry != '.' && $entry != '..' && (($ext && preg_match($exts, $entry) || !$ext) || $sub && is_dir($file)) && !in_array($entry, $skips)) {
            if ($sub && is_dir($file)) {
                checkfiles($file . '/', $ext, $sub, $skip);
            } else {
                if (is_dir($file)) {
                    $_G["md5data"][$file] = md5($file);
                } else {
                    $_G["md5data"][$file] = md5_file($file);
                }
            }
        }
    }
}

/**
 * 保存文件校验信息
 */
function savecheckfiles($file = RUNTIME_PATH . './tickyphp.md5') {
    global $_G;
    $fh = fopen($file, "w+");
    foreach ($_G["md5data"] as $key => $value) {
        $msg = $value . ' *' . $key . PHP_EOL;
        fwrite($fh, $msg);
    }
    fclose($fh);
}

/**
 * 根据生日计算星座
 * @param int $birthday 年份 格式如：2018-05-06
 * @return str
 */
function get_constellation($birthday) {
    $month = intval(substr($birthday, 5, 2));
    $day = intval(substr($birthday, 8, 2));
    if ($month < 1 || $month > 12 || $day < 1 || $day > 31) {
        return NULL;
    }
    $signs = array(
        array('20' => '水瓶座'),
        array('19' => '双鱼座'),
        array('21' => '白羊座'),
        array('20' => '金牛座'),
        array('21' => '双子座'),
        array('22' => '巨蟹座'),
        array('23' => '狮子座'),
        array('23' => '处女座'),
        array('23' => '天秤座'),
        array('24' => '天蝎座'),
        array('22' => '射手座'),
        array('22' => '摩羯座')
    );
    list($start, $name) = each($signs[$month - 1]);
    if ($day < $start) {
        list($start, $name) = each($signs[($month - 2 < 0) ? 11 : $month - 2]);
    }
    return $name;
}

/**
 *  根据生日计算生肖 传入$birthday格式如：2018
 * @param int $year 年份
 * @return str
 */
function get_animal($year) {
    $animals = array(
        '鼠', '牛', '虎', '兔', '龙', '蛇',
        '马', '羊', '猴', '鸡', '狗', '猪'
    );
    $key = ($year - 1900) % 12;
    return $animals[$key];
}

/**
 * 提交表单
 */
function submitcheck($var, $allowget = 0, $seccodecheck = 0, $secqaacheck = 0) {
    if (!$_GET[$var]) {
        return FALSE;
    } else {
        if ($allowget || ($_SERVER['REQUEST_METHOD'] == 'POST' && !empty($_GET['formhash']) && $_GET['formhash'] == FORMHASH &&
                empty($_SERVER['HTTP_X_FLASH_VERSION']) && (empty($_SERVER['HTTP_REFERER']) ||
                preg_replace("/https?:\/\/([^\:\/]+).*/i", "\\1", $_SERVER['HTTP_REFERER']) == preg_replace("/([^\:]+).*/", "\\1", $_SERVER['HTTP_HOST'])))) {
            return TRUE;
        } else {
            $msg .= "REQUEST_METHOD:" . $_SERVER['REQUEST_METHOD'] . "<br>";
            $msg .= "formhash:" . $_GET['formhash'] . "=" . FORMHASH . "<br>";
            $msg .= "HTTP_X_FLASH_VERSION:" . $_SERVER['HTTP_X_FLASH_VERSION'] . "<br>";
            $msg .= "HTTP_REFERER:" . $_SERVER['HTTP_REFERER'] . "<br>";
            $msg .= "HTTP_HOST:" . $_SERVER['HTTP_HOST'] . "<br>";
            showmsg($msg . L('submit_invalid'));
        }
    }
}

function dir_writeable($dir) {
    $writeable = 0;
    if (!is_dir($dir)) {
        @mkdir($dir, 0777);
    }
    if (is_dir($dir)) {
        if ($fp = @fopen("$dir/test.txt", 'w')) {
            @fclose($fp);
            @unlink("$dir/test.txt");
            $writeable = 1;
        } else {
            $writeable = 0;
        }
    }
    return $writeable;
}
